<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\Constants\ErrorCode;
use App\Constants\SuccessCode;
use App\Exception\BusinessException;
use App\Request\ImageUploadRequest;
use App\Resource\BaseResource;
use Carbon\Carbon;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Utils\Str;
use PhpOffice\PhpSpreadsheet\IOFactory;

class File extends AbstractController
{
    public function uploadImage(ImageUploadRequest $request, ResponseInterface $response)
    {
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            /** @var UploadedFile $file */
            $file = $request->file('file');
            if ($file->getSize() <= 0) {
                throw new BusinessException(ErrorCode::FILE_UPLOAD_ERROR);
            }

            $extension = $file->getExtension();
            $uploadDir = BASE_PATH . '/public/upload/' . Carbon::now()->toDateString() . DIRECTORY_SEPARATOR;

            if (! is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $filename = Str::random(10) . '.' . $extension;
            $filePath = $uploadDir . $filename;

            $originImage = 'upload' . DIRECTORY_SEPARATOR . Carbon::now()->toDateString() . DIRECTORY_SEPARATOR . $filename;

            $returnPath = env('HOST_NAME') . DIRECTORY_SEPARATOR . $originImage;

            $file->moveTo($filePath);

            chmod($filePath, 0755);
            if ($file->isMoved()) {

                return new BaseResource(SuccessCode::SUCCESS, [
                    'image_path' => $returnPath,
                ]);
            }
            throw new BusinessException(ErrorCode::FILE_UPLOAD_ERROR);
        } else {
            throw new BusinessException(ErrorCode::FILE_UPLOAD_ERROR);
        }
    }

    public function uploadTyintImage(ImageUploadRequest $request, ResponseInterface $response)
    {
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            /** @var UploadedFile $file */
            $file = $request->file('file');
            if ($file->getSize() <= 0) {
                throw new BusinessException(ErrorCode::FILE_UPLOAD_ERROR);
            }

            $path = $file->getPath();

            $extension = $file->getExtension();

            $uploadDir = BASE_PATH . '/public/upload/' . Carbon::now()->toDateString() . DIRECTORY_SEPARATOR;

            if (! is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $filename = Str::random(10) . '.' . $extension;

            $filePath = $uploadDir . $filename;

            $originImage = 'upload' . DIRECTORY_SEPARATOR . Carbon::now()->toDateString() . DIRECTORY_SEPARATOR . $filename;

            $returnPath = env('HOST_NAME') . DIRECTORY_SEPARATOR . $originImage;

            $file->moveTo($filePath);

            chmod($filePath, 0755);
            if ($file->isMoved()) {
                return [
                    'errno' => 0,
                    'data' => [
                        'url' => $returnPath,
                        'alt' => '',
                        'href' => ''
                    ]
                ];
            }
            return [
                'errno' => 1,
                'message' => "图片上传失败"
            ];
        } else {
            return [
                'errno' => 1,
                'message' => "图片上传失败"
            ];
        }
    }

    public function uploadExcel(RequestInterface $request)
    {
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            /** @var UploadedFile $file */
            $file = $request->file('file');
            if ($file->getSize() <= 0) {
                throw new BusinessException(ErrorCode::FILE_UPLOAD_ERROR);
            }

            $extension = $file->getExtension();

            if(!in_array($extension, ['xls', 'xlsx'])) {

                throw new BusinessException(ErrorCode::CUSTOM_ERROR . '文件格式必须为xlsx | xls');
            }

            $uploadDir = BASE_PATH . '/public/excel/' . Carbon::now()->toDateString() . DIRECTORY_SEPARATOR;

            if (! is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $filename = Str::random(10) . '.' . $extension;
            $filePath = $uploadDir . $filename;

            $file->moveTo($filePath);

            chmod($filePath, 0755);
            if ($file->isMoved()) {

                $reader = IOFactory::createReader(ucfirst($extension));

                $spreadsheet = $reader->load($filePath);

                $worksheet = $spreadsheet->getActiveSheet();

                $highestRow = $worksheet->getHighestRow();
                $highestColumn = $worksheet->getHighestColumn();

                $phone_list = [];

                for ($row = 1; $row <= $highestRow; $row++) {
                    // 逐列读取
                    for ($col = 'A'; $col <= $highestColumn; $col++) {
                        // 获取单元格的值
                        $cellValue = $worksheet->getCell($col . $row)->getValue();
                        if (isElevenDigitNumber((string)$cellValue)) {

                            $phone_list[] = $cellValue;
                        }
                    }
                }
                return new BaseResource(SuccessCode::SUCCESS, $phone_list);
            }
            throw new BusinessException(ErrorCode::FILE_UPLOAD_ERROR);
        } else {
            throw new BusinessException(ErrorCode::FILE_UPLOAD_ERROR);
        }
    }
}
